package consulRegister

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"strconv"
)

var client *api.Client
var err error
var ServiceID string
var ServiceName string
var ServicePort int
func init()  {
	config := api.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client,err = api.NewClient(config)
	ServiceID = "userservice" + uuid.New().String()
}
func SetServiceNameAndPort(name string,port int)  {
	ServiceName = name
	ServicePort = port
}
func RegService()  {
	reg := api.AgentServiceRegistration{}
	reg.ID = ServiceID
	reg.Name = ServiceName
	reg.Address = "127.0.0.1"
	reg.Port = ServicePort
	reg.Tags = []string{"primary"}
	check := api.AgentServiceCheck{}
	check.Interval = "5s"
	check.HTTP = "http://127.0.0.1:"+strconv.Itoa(ServicePort)+"/health"
	reg.Check = &check
	if err != nil{
		fmt.Println(err)
		return
	}
	err = client.Agent().ServiceRegister(&reg)
}

func Unregservice()  {
	client.Agent().ServiceDeregister(ServiceID)
}

